package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.entity.*;
import io.renren.common.redis.RedisUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.dao.XlsSysConfigsDao;
import io.renren.dao.XlsUserAwardDao;
import io.renren.dao.XlsUsersBankcardsDao;
import io.renren.dao.XlsUsersDrawsDao;
import io.renren.dto.XlsUsersDrawsDTO;
import io.renren.service.XlsLogCashService;
import io.renren.service.XlsUserService;
import io.renren.service.XlsUsersDrawsService;
import io.renren.utils.AppResult;
import io.renren.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户提现记录
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-04-13
 */
@Service
public class XlsUsersDrawsServiceImpl extends CrudServiceImpl<XlsUsersDrawsDao, XlsUsersDrawsEntity, XlsUsersDrawsDTO> implements XlsUsersDrawsService {

    @Autowired
    private XlsUsersDrawsDao xlsUsersDrawsDao;
    @Autowired
    private XlsUserService xlsUserService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private XlsUserAwardDao xlsUserAwardDao;
    @Autowired
    private XlsUsersBankcardsDao xlsUsersBankcardsDao;
    @Autowired
    private XlsSysConfigsDao xlsSysConfigsDao;
    @Autowired
    private XlsLogCashService xlsLogCashService;


    @Override
    public QueryWrapper<XlsUsersDrawsEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<XlsUsersDrawsEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    @Transactional
    public AppResult destoonFinanceCash(String paypassword, String bankCardId, Long userId, BigDecimal cash, Integer type) {
        Object o = redisUtils.get(userId + "destoonFinanceCash");
        if (StringUtils.isNotNull(o)){
            return AppResult.ERROR("请勿重复操作！");
        }
        redisUtils.set(userId+"destoonFinanceCash",userId,5L);
        if (userId!=null){
            Map<String,Object> map=xlsUserService.checkPayPassWorld(userId,paypassword);
            if("-1".equals(map.get("status").toString())){
                TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                redisUtils.delete(userId + "destoonFinanceCash");
                return AppResult.ERROR(map.get("msg").toString());
            }
            Map<String, Object> resultMap = userDraws(userId, cash, type, bankCardId);
            if ("0".equals(resultMap.get("status").toString())){
                redisUtils.delete(userId + "destoonFinanceCash");
                return AppResult.OK("提现成功！");
            }else {
                TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                return AppResult.ERROR(resultMap.get("msg").toString());
            }
        }else {
            redisUtils.delete(userId + "destoonFinanceCash");
            return AppResult.ERROR("申请用户不能为空!");
        }
    }

    /**
     * 提现逻辑
     * @param userId
     * @param cash
     * @param type
     * @param bankCardId
     * @return
     */
    private Map<String, Object> userDraws(Long userId, BigDecimal cash, Integer type, String bankCardId) {
        Map<String,Object> resultMap=new HashMap<>();
        try{
            if ("".equals(bankCardId) ||bankCardId==null ){
                resultMap.put("status","500");
                resultMap.put("msg","请选择银行卡");
                return resultMap;
            }
            String drawNo = StringUtils.getOrderIdByTime("T");
            XlsUserAwardEntity account = xlsUserAwardDao.selectUserAwardByUserId(userId);
            BigDecimal awardPrice = account.getAwardPrice();
            BigDecimal changeCash=BigDecimal.ZERO;
            if (cash.compareTo(BigDecimal.ZERO)!=1){
                resultMap.put("status","500");
                resultMap.put("msg","提现金额有误");
                return resultMap;
            }
            XlsUsersBankcardsEntity usersBankcards = xlsUsersBankcardsDao.selectById(Long.valueOf(bankCardId));
            if (null!=usersBankcards){
                if (!userId.equals(usersBankcards.getUserId())){
                    resultMap.put("status","500");
                    resultMap.put("msg","银行卡信息有误请确认卡号是否正确");
                    return resultMap;
                }
            }
            BigDecimal changeRateCash=BigDecimal.ZERO;
            if (5==type){
                BigDecimal rewardCash = account.getAwardPrice();
                if (rewardCash.compareTo(cash)==-1){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    resultMap.put("status","500");
                    resultMap.put("msg","提现金额大于账户可提现余额请重新申请");
                    return resultMap;
                }
                XlsSysConfigsEntity sysConfigs = xlsSysConfigsDao.selectFieldValueByFieldCode("awarRate"); // 奖励钱包提现费率
                String rewardRates = sysConfigs.getFieldValue();
                BigDecimal rewardRate=new BigDecimal(rewardRates);
                changeRateCash = cash.multiply(rewardRate);//应交费率金额
                changeCash=cash.subtract(changeRateCash);//实际到账金额
                //费用流水
                XlsLogCashEntity logCash = xlsLogCashService.intiLogCash(24, userId, userId, drawNo, rewardCash, -1, changeRateCash, "奖励账户提现手续费");
                xlsLogCashService.insert(logCash);
                //提现流水
                XlsLogCashEntity logCash1 = xlsLogCashService.intiLogCash(25, userId, userId, drawNo, rewardCash.subtract(changeRateCash).setScale(2,BigDecimal.ROUND_DOWN), -1, changeCash.setScale(2,BigDecimal.ROUND_DOWN), "奖励账户提现");
                xlsLogCashService.insert(logCash1);
                account.setAwardPrice(rewardCash.subtract(cash).setScale(2,BigDecimal.ROUND_DOWN));
                int i=xlsUserAwardDao.updateById(account);
                if (i<1){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    resultMap.put("status","500");
                    resultMap.put("msg","申请提现失败");
                    return resultMap;
                }
            }
            //生成提现订单号
            XlsUsersDrawsEntity usersDraws=new XlsUsersDrawsEntity();
            usersDraws.setDrawNo(drawNo);
            usersDraws.setUserId(userId.toString());
            usersDraws.setCash(cash);
            usersDraws.setRealCash(changeCash);
            usersDraws.setTaxratio(changeRateCash);
            usersDraws.setAccount(bankCardId);
            usersDraws.setCashStatus(2);
            usersDraws.setCreateTime(new Date());
            usersDraws.setType(type);
            xlsUsersDrawsDao.insert(usersDraws);
            resultMap.put("status","0");
            resultMap.put("msg","申请提现成功");
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("status","500");
            resultMap.put("msg","申请提现失败");
        }
        return resultMap;

    }






}